<?php
	 $root_dir = realpath(dirname(__FILE__));
    include_once($root_dir."/config/config.php");
    define('APP_DIR',ROOT_DIR."/app/");
    include_once(APP_DIR."/base/defined.php");
    
    require(ROOT_DIR.'/app/base/kernel.php');
    if(!kernel::register_autoload()){
        require(APP_DIR.'/base/autoload.php');
    }

		$db = kernel::database();
		$sql = "select * FROM sdb_tbdata_hellomoto WHERE content2 is not null;";

		$db_rs = $db->exec($sql);
		$rs = $db_rs['rs'];

		$fp = fopen('d:\1512_etao2.csv', 'a');
		$i = 0;

		while($product = mysql_fetch_assoc($rs)){

			$html = tbdata_html_object::str_get_html(base64_decode($product['content2']) );

			$merchants = $html->find('table.contrast-table tr td.merchant-name div.merchant-title img');
			$merchant_logo = $merchant_name = $goods_name = $goods_href = $goods_price = $rows = array();
			foreach($merchants as $merchant){
				$merchant_logo[] = $merchant->src;
				$merchant_name[] = $merchant->title;
			}
			$goods = $html->find('table.contrast-table tr td.goods div.name a');
			foreach($goods as $g){
				$goods_name[] = $g->innertext;
				$goods_href[] = $g->href;
			}

			$goods = $html->find('table.contrast-table tr td.goods div.price');
			foreach($goods as $g){
				$goods_price[] = $g->innertext;
			}
			foreach($merchant_logo as $key=>$logo){
				if($merchant_name[$key]=='淘宝网') continue;
				$rows[$key]['click_url'] = $goods_href[$key];
				$rows[$key]['title'] = $goods_name[$key];
				$rows[$key]['price'] = $goods_price[$key];
				$rows[$key]['merchant'] = $merchant_name[$key];
				$rows[$key]['platform'] = $merchant_name[$key];
				$rows[$key]['merchant_logo'] = $merchant_logo[$key];
			}


			foreach ((array)$rows as $fields) {
				$fields['product_id'] = $product['product_id'];
				$fields['keyword'] = $product['keyword'];
				if($i==0){
					fputcsv($fp, array_keys($fields));
					$i++;
				}
				fputcsv($fp, $fields);
			}
			if($i++%50==0){
				echo $i."\n";
			}
		}